//
//  DWDraggingView.m
//  DWDraggingView
//
//  Created by Devwan on 2017/4/12.
//  Copyright © 2017年 Devwan. All rights reserved.
//

#import "DWDraggingView.h"

@implementation DWDraggingView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        CGRect newframe = frame;
        newframe.origin.y = 20 + 44;
        newframe.size.height = 50;
        newframe.size.width = 50;
        self.frame = newframe;
        self.layer.cornerRadius = 25;
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 起始点位置
    beginPoint = [[touches anyObject] locationInView:self];
    
    // view前置
    [[self superview] bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 当前位置
    CGPoint currentPoint = [[touches anyObject] locationInView:self];
    
    // 偏移变量
    CGFloat offsetX = currentPoint.x - beginPoint.x;
    CGFloat offsetY = currentPoint.y - beginPoint.y;
    
    // newCenter
    CGFloat newCenterX = self.center.x + offsetX;
    CGFloat newCenterY = self.center.y + offsetY;
    CGPoint newCenter = CGPointMake(newCenterX, newCenterY);
    
    // 限制view移动范围
    CGFloat halfX = CGRectGetMidX(self.bounds);
    // x坐标左边界 & 右边界
    newCenter.x = MAX(halfX, newCenter.x);
    newCenter.x = MIN(self.superview.bounds.size.width - halfX, newCenter.x);
    // y
    CGFloat halfY = CGRectGetMidY(self.bounds);
    newCenter.y = MAX(halfY, newCenter.y);
    newCenter.y = MIN(self.superview.bounds.size.height - halfY, newCenter.y);
    self.center = newCenter;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didTouchesMovedWithPosition:)]) {
        [self.delegate didTouchesMovedWithPosition:[self judgmentPositionType]];
    }
}

/*
 当前位置判断，有以下三种情况：
 1、centerX < 1/3                 左边
 2、centerX > 1/3 & centerX < 2/3 中间
 3、centerX > 2/3                 右边
 */
- (DWPositionType)judgmentPositionType {
    
    CGFloat centerX =  self.center.x;
    
    if (centerX < kSCREEN_WIDTH / 3) {
        return DWPositionTypeLeft;
    } else if (centerX > kSCREEN_WIDTH / 3 && centerX < kSCREEN_WIDTH / 3 * 2) {
        return DWPositionTypeMiddle;
    } else {
        return DWPositionTypeRight;
    }
}


@end
